package main

import (
	"flag"
	"fmt"
	"net/http"

	"longbri/api/main/internal/config"
	"longbri/api/main/internal/handler"
	"longbri/api/main/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
)

var configFile = flag.String("f", "etc/main-api.yaml", "the config file")

func CorsMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 设置允许的源
		w.Header().Set("Access-Control-Allow-Origin", "*")
		// 设置允许的请求头类型
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
		// 设置允许的请求方法
		w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
		// 允许携带凭证（如 Cookie 等，根据实际需求决定是否设置）
		w.Header().Set("Access-Control-Allow-Credentials", "true")

		if r.Method == http.MethodOptions {
			// 对于 OPTIONS 请求，直接返回 200 状态码
			httpx.WriteJson(w, http.StatusOK, map[string]interface{}{})
			return
		}

		next(w, r)
	}
}

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	//注册全局错误处理器
	//httpx.SetErrorHandler(err.ErrHandler)
	server.Use(CorsMiddleware)

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
